<div class="row">
    <div class="col-md-4" style="margin-bottom: 15px; margin-left: 5px">
        <button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal1">
            添加任务
        </button>
    </div>
    <div class="row">
        <div class="col-md-8">
            <div id="mission_list" style="margin-left: 20px">
                <div class="box box-success">
                    <div class="box-header" style="cursor: move; height: 50px">
                        <i class="fa fa-tasks"></i>
                        <h3 class="box-title">任务：{0}</h3>
                        <div class="pull-right box-tools">
                            <div class="btn-group" data-toggle="btn-toggle">
                                <button type="button" class="btn btn-default {2}" onclick="start_mission('{4}')">
                                    <i class="fa fa-play text-green"></i>
                                </button>
                                <button type="button" class="btn btn-default {3}" onclick="stop_mission('{4}')">
                                    <i class="fa fa-square text-red"></i>
                                </button>
                            </div>
                            <div class="btn-group">
                                <!--TABLE_CHI = ['新闻数据', '店铺数据', '店铺评论数据', '商品数据', '商品评论数据'];-->
                                <!--TABLE_ARR = ['Article', 'ECommerceShop', 'ECommerceShopComment', 'ECommerceGood', 'ECommerceGoodComment'];-->
                                <button type="button" class="btn btn-default dropdown-toggle"
                                        data-toggle="dropdown" aria-expanded="true">
                                    <i class="fa fa-bars"></i></button>
                                <ul class="dropdown-menu pull-right" role="menu">
                                    <li><a href="#" onclick="show_table_model('Article', '{0}')">新闻数据展示</a></li>
                                    <li class="divider"></li>
                                    <li><a href="#" onclick="show_table_model('ECommerceShop', '{0}')">店铺数据展示</a></li>
                                    <li><a href="#"
                                           onclick="show_table_model('ECommerceShopComment', '{0}')">店铺评论数据展示</a></li>
                                    <li><a href="#" onclick="show_table_model('ECommerceGood', '{0}')">商品数据展示</a></li>
                                    <li><a href="#"
                                           onclick="show_table_model('ECommerceGoodComment', '{0}')">商品评论数据展示</a></li>
                                </ul>
                            </div>
                            <button type="button" class="btn btn-default" data-widget="collapse"><i
                                    class="fa fa-minus"></i>
                            </button>
                            <button type="button" class="btn btn-default"
                                    onclick="delete_mission('{0}')"><i class="fa fa-times"></i>
                            </button>
                        </div>
                    </div>
                    <div class="box-body">
                        <div class="row">
                            <div class="col-md-12">
                                <p><strong>爬虫起止时间：</strong>{6} &nbsp;&nbsp; ~ &nbsp;&nbsp;{7}</p>
                            </div>
                            <div class="col-md-12">
                                <ul class="list-group">
                                    {5}
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div style="margin-right: 20px">
                <div class="box box-success">
                    <div class="box-header" style="cursor: move; height: 50px">
                        <i class="fa  fa-gg"></i>
                        <h3 class="box-title">工作中的子任务</h3>
                    </div>
                    <div class="box-body">
                        <table class="table table-border table-bg table-bordered" id="myrTable">
                            <thead id="rtab_head">

                            </thead>
                            <tbody id="rtab_dat">

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

<div class="modal" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span></button>
                <h4 class="modal-title">添加任务（第一步：输入URLS）</h4>
            </div>
            <div class="modal-body">
                <form action="" method="post" class="form form-horizontal responsive">
                    <div class="form-group">
                        <div class="formControls col-xs-12">
                            <input type="text" class="form-control" id="name" placeholder="任务名，不能含有中文">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="formControls col-xs-12">
                        <textarea cols="" rows="24" class="textarea form-control" id="urls"
                                  placeholder="请输入URLS，每行一个URL"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-success" onclick="step1()">确认</button>
            </div>
        </div>
    </div>
</div>

<div class="modal" id="myModal2"
     tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span></button>
                <h4 class="modal-title">添加任务（第二步：配置子任务）</h4>
            </div>
            <div class="modal-body">
                <form action="" method="post" class="form form-horizontal responsive">
                    <div id="sub_list">
                        <div class="form-group">
                            <label class="col-xs-2 control-label">任务名</label>
                            <div class="formControls col-xs-10">
                                <input type="text" class="form-control"
                                       id="{0}" value="{1}" disabled>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-xs-2 control-label">爬虫名</label>
                            <div class="formControls col-xs-10">
                                <input type="text" class="form-control"
                                       id="{2}" value="{3}" disabled>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-xs-2 control-label">配置</label>
                            <div class="formControls col-xs-10">
                                <select class="form-control select_list" id="{4}">
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-xs-2 control-label">优先度</label>
                            <div class="formControls col-xs-10">
                                <input type="text" class="form-control"
                                       id="{6}" value="{7}" placeholder="1~9">
                            </div>
                        </div>
                        <hr style="height:1px;border:none;border-top:1px double forestgreen;"/>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-success" onclick="step2()">确认</button>
            </div>
        </div>
    </div>
</div>

<div class="modal" id="myModal3"
     tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span></button>
                <h4 class="modal-title">添加任务（第三步：配置资源）</h4>
            </div>
            <div class="modal-body">
                <form action="" method="post" class="form form-horizontal responsive">
                    <div class="form-group">
                        <label class="col-xs-2 control-label">权重</label>
                        <div class="formControls col-xs-10">
                            <input type="text" class="form-control" id="st3_weight">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-xs-2 control-label">开始时间</label>
                        <div class="formControls col-xs-10">
                            <div class="input-append date form_datetime">
                                <input size="16" type="text" value="" class="form-control" id="st3_st_time">
                                <span class="add-on"><i class="icon-remove"></i></span>
                                <span class="add-on"><i class="icon-calendar"></i></span>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-xs-2 control-label">结束时间</label>
                        <div class="formControls col-xs-10">
                            <div class="input-append date form_datetime">
                                <input size="16" type="text" value="" class="form-control" id="st3_ed_time">
                                <span class="add-on"><i class="icon-remove"></i></span>
                                <span class="add-on"><i class="icon-calendar"></i></span>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-xs-2 control-label">Redis资源</label>
                        <div class="formControls col-xs-10">
                            <select class="form-control Redis_list" id="st3_Redis">
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-xs-2 control-label">Mysql资源</label>
                        <div class="formControls col-xs-10">
                            <select class="form-control Mysql_list" id="st3_Mysql">
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-xs-2 control-label">Mongo资源</label>
                        <div class="formControls col-xs-10">
                            <select class="form-control Mongo_list" id="st3_Mongo">
                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-default" onclick="step3(false)">添加任务</button>
                <button type="button" class="btn btn-success" onclick="step3(true)">添加任务并启动</button>
            </div>
        </div>
    </div>
</div>

<div class="modal" id="myModal4"
     tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" style="width: 1280px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span></button>
                <h4 class="modal-title">爬虫结果数据展示</h4>
            </div>
            <div class="modal-body">
                <table class="table table-border table-bg table-bordered" id="myTable">
                    <thead id="tab_head">

                    </thead>
                    <tbody id="tab_dat">

                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>


<link rel="stylesheet" type="text/css" href="plugins/datatables/jquery.dataTables.min.css"/>
<script type="text/javascript" src="plugins/datatables/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="plugins/datatables/dataTables.bootstrap.min.js"></script>

<script type="text/javascript" src="../const.js"></script>
<script type="text/javascript" src="mycommon.js"></script>

<script>
    TABLE_ARR = ['Article', 'ECommerceShop', 'ECommerceShopComment', 'ECommerceGood', 'ECommerceGoodComment'];
    TABLE_CHI = ['新闻数据', '店铺数据', '店铺评论数据', '商品数据', '商品评论数据'];
    function show_table_model(table, name) {
        $("#myModal4").modal("toggle");
        $('#tab_head').empty();
        $('#tab_dat').empty();
        var GET_URL = POST_URL_PREFIX + "/get_table_of_mission?table_name=" + table + "&mission_name=" + name;
        console.log(GET_URL);
        $.get(GET_URL).success(function (dat) {
            console.log(dat);
            for (var i = 0; i < dat.length; ++i) {
                var str = '<tr>';
                for (var j = 0; j < dat[i].length; ++j) {
                    str += '<th>' + dat[i][j] + '</th>';
                }
                str += '</tr>';
                if (i === 0) {
                    $('#tab_head').append(str);
                } else {
                    $('#tab_dat').append(str);
                }
            }
            $(document).ready(function () {
                $('#myTable').DataTable();
            });
        });
    }
</script>

<script>
    function show_chart_model(name, sub) {
        console.log("显示图...", name, sub);
        window.open("/monitor?spider_name=" + sub);
    }
</script>

<script>
    function timestamp2str(val) {
        return new Date(val * 1000).toLocaleString();
    }
    function render_html_list(dat) {
        var id_type = "#mission_list";
        var html = _misson_mgr_html_cache;
        $(id_type).empty();
        for (var i = 0; i < dat.length; ++i) {
            var cur = dat[i];
            var detail = cur["detail"];

            var btn_html = ""; // 子任务按钮组html
            for (var j = 0; j < detail.submission_list.length; ++j) {
                var sub_name = detail.submission_list[j].name;
                var sub_btn_html = '<li class="list-group-item"><center><a onclick="show_chart_model(\'{1}\', \'{2}\')" href="#">{0} 监控</a></center></li>';
                btn_html += sub_btn_html.format(sub_name, cur.name, sub_name);
            }

            var ins = html.format(
                cur["name"],
                JSON.stringify(cur),
                detail["state"] === "START" ? "active" : "",
                detail["state"] === "STOP" ? "active" : "",
                i,
                btn_html,
                timestamp2str(detail["start_time"]),
                timestamp2str(detail["end_time"])
            );
            $(id_type).append(ins);
        }
    }
    function init_list() {
        var id_type = "#mission_list";
        _misson_mgr_html_cache = $(id_type).html();
        var GET_URL = POST_URL_PREFIX + "/get_all_mission";
        console.log(GET_URL);
        $.get(GET_URL).success(function (dat) {
            console.log(dat);
            _main_dat_list_cache = dat;
            render_html_list(dat);
        });
    }
    init_list();
    function start_mission(index) {
        var name = _main_dat_list_cache[index]["name"];
        var GET_URL = POST_URL_PREFIX + "/mission_start?name=" + name;
        console.log(GET_URL);
        $.get(GET_URL).success(function (dat) {
            _main_dat_list_cache[index]["detail"]["state"] = "START";
            render_html_list(_main_dat_list_cache);
        });
    }
    function stop_mission(index) {
        var name = _main_dat_list_cache[index]["name"];
        var GET_URL = POST_URL_PREFIX + "/mission_stop?name=" + name;
        console.log(GET_URL);
        $.get(GET_URL).success(function (dat) {
            _main_dat_list_cache[index]["detail"]["state"] = "STOP";
            render_html_list(_main_dat_list_cache);
        });
    }
</script>

<script>
    function init_right_list() {
        $('#rtab_head').empty();
        $('#rtab_dat').empty();
        var GET_URL = POST_URL_PREFIX + "/get_top_submissions";
        console.log(GET_URL);
        $.get(GET_URL).success(function (dat) {
            console.log(dat);
            for (var i = 0; i < dat.length; ++i) {
                var str = '<tr>';
                for (var j = 0; j < dat[i].length; ++j) {
                    str += '<th>' + dat[i][j] + '</th>';
                }
                str += '</tr>';
                if (i === 0) {
                    $('#rtab_head').append(str);
                } else {
                    $('#rtab_dat').append(str);
                }
            }
//            $(document).ready(function () {
//                $('#myrTable').DataTable();
//            });
        });
    }
    init_right_list();
</script>

<script>
    function delete_mission(name) {
        if (confirm("注意：真的删除任务: " + name + "?")) {
            var GET_URL = POST_URL_PREFIX + "/delete_mission?name=" + name;
            console.log(GET_URL);
            $.getJSON(GET_URL).success(function (dat) {
                console.log(dat);
                alert("操作成功！");
                reload_content();
            });
        }
    }
</script>

<script>
    function is_vilid_name(str) {
        var ch_reg = /^[0-9a-zA-Z_]+$/;
        return ch_reg.test(str);
    }
</script>

<script>
    function step1() {
        mission_name = $("#name").val();
        if (!is_vilid_name(mission_name)) {
            alert("任务名不能含有中文！");
            return;
        }
        var urls = $("#urls").val().split("\n");
        var POST_URL = POST_URL_PREFIX + "/get_default_submissions_by_target_urls";
        console.log(POST_URL);
        $.post(POST_URL, {urls: JSON.stringify(urls), mission_name: mission_name})
            .success(function (result) {
                _list2_cache = result;
                console.log(result);
                $("#myModal1").modal("toggle");
                show_model2(result);
            });
    }
    function init_select_list(lists) {
        var GET_URL = POST_URL_PREFIX + "/get_settings_name";
        var html = '<option value="{0}">{0}</option>';
        console.log(GET_URL);
        $.get(GET_URL).success(function (dat) {
            for (var i = 0; i < dat.length; ++i) {
                var cur = dat[i];
                var ins = html.format(cur);
                $(".select_list").each(function () {
                    $(this).append(ins);
                });
            }
            for (i = 0; i < lists.length; ++i) {
                cur = lists[i]["detail"]["settings"];
                var id = "#inp" + (i * 4 + 2);
                var find = "option[value='{0}']".format(cur);
                $(id).find(find).attr("selected", "selected");
            }
        });
    }
    _show_model2_html_cache = "";
    function show_model2(dat) {
        $("#myModal2").modal("toggle");

        var id_type = "#sub_list";
        if (_show_model2_html_cache === "") {
            _show_model2_html_cache = $(id_type).html();
        }
        var html = _show_model2_html_cache;
        $(id_type).empty();

        console.log(dat);
        cnt = 0;
        for (i = 0; i < dat.length; ++i) {
            var cur = dat[i];
            console.log(JSON.stringify(cur));
            var detail = cur["detail"];
            var ins = html.format(
                "inp" + cnt++, cur["name"],
                "inp" + cnt++, detail["spider_name"],
                "inp" + cnt++, detail["settings"],
                "inp" + cnt++, detail["priority"]
            );
            $(id_type).append(ins);
        }
        init_select_list(dat);
    }
    function step2() {
        for (i = 0; i < _list2_cache.length; ++i) {
            var settings_id = (i * 4 + 2);
            var priority_id = (i * 4 + 3);
            _list2_cache[i]["detail"]["settings"]
                = $("#inp{0} option:selected".format(settings_id)).text();
            _list2_cache[i]["detail"]["priority"]
                = $("#inp{0}".format(priority_id)).val();
        }
        show_model3();
    }
    function show_model3() {
        $("#myModal2").modal("toggle");
        $("#myModal3").modal("toggle");
        $.fn.datetimepicker.dates['zh'] = {
            days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
            daysShort: ["日", "一", "二", "三", "四", "五", "六", "日"],
            daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
            months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            monthsShort: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],
            meridiem: ["上午", "下午"],
            today: "跳转到当前时间"
        };
        $(".form_datetime").datetimepicker({
            lang: "ch",
            format: "yyyy-mm-dd hh:ii",
            autoclose: true,
            todayBtn: true,
            minuteStep: 1,
            todayHighlight: true,
            weekStart: 1,
            language: 'zh',
            initialDate: new Date()
        });
        var GET_URL = POST_URL_PREFIX + "/get_resources";
        var html = '<option value="{0}">{0}</option>';
        console.log(GET_URL);
        $.get(GET_URL).success(function (dat) {
            console.log(dat);
            for (var i = 0; i < dat.length; ++i) {
                var cur = dat[i];
                var ins = html.format(cur["name"]);
                var id = "." + cur["type"] + "_list";
                $(id).append(ins);
            }
        });
    }
    function to_timestamp(stringTime) {
        var timestamp2 = Date.parse(new Date(stringTime));
        timestamp2 = timestamp2 / 1000;
        console.log(stringTime + "的时间戳为：" + timestamp2);
        return timestamp2;
    }
    function step3(is_start) {
        var result = {
            name: mission_name,
            detail: {
                start_time: to_timestamp($("#st3_st_time").val()),
                end_time: to_timestamp($("#st3_ed_time").val()),
                submission_list: _list2_cache,
                resource_dic: {
                    filter_redis: $("#st3_{0} option:selected".format("Redis")).text(),
                    mongo: $("#st3_{0} option:selected".format("Mongo")).text(),
                    mysql: $("#st3_{0} option:selected".format("Mysql")).text()
                },
                weight: $("#st3_weight").val(),
                state: is_start ? "START" : "STOP"
            }
        };
        result = JSON.stringify(result);
        console.log(result);
        var POST_URL = POST_URL_PREFIX + "/add_mission";
        console.log(POST_URL);
        $.post(POST_URL, {json_result: result}).success(function () {
            alert("操作成功！");
            $("#myModal3").modal("toggle");
            reload_content();
        });
    }
</script>
